#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

# python imports
import logging
from os import path
import urllib
import random
import sha

# google imports
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import mail

# API gdata
import gdata.service
import gdata.urlfetch
import gdata.alt.appengine

# textlocutor imports
import core_settings
from core.models import CoreUser
from core.utils import reset_token
import core

#http://googledataapis.blogspot.com/2008/04/release-hounds-support-for-app-engine.html
gdata.service.http_request_handler = gdata.urlfetch

class CoreUserPage(core.BaseRequestHandler):
    def get(self):
        user = users.get_current_user()
        coreuser = CoreUser.all().filter('user =', user).get()
        template_values = {
            'user' : coreuser,
            'base_url': self.request.application_url,
            'logout_url': users.CreateLogoutURL(self.request.uri),
            }
        self.generate(template_values, 'user.html')

    def post(self):
        user = users.get_current_user()
        coreuser = CoreUser.all().filter('user =', user).get()
        coreuser.nick = self.request.POST['nickname']
        coreuser.put()
        self.redirect(self.request.application_url)

class CoreUserDelete(core.BaseRequestHandler):
    def get(self):
        user = users.get_current_user()
        coreuser = CoreUser.all().filter('user =', user).get()
        template_values = {
            'user' : coreuser,
            'base_url': self.request.application_url,
            'logout_url': users.CreateLogoutURL(self.request.uri),
            }
        self.generate(template_values, 'delete.html')

    def post(self):
        user = users.get_current_user()
        coreuser = CoreUser.all().filter('user =', user).get()

        for app in core_settings.EXTRA_APPS:
            module = __import__('%s.models' % app)
            try:
                module.models.del_user_db(coreuser)
            except AttributeError:
                # This exception is raised when the app doesn't need
                # any last deletion
                pass

        coreuser.delete()
        message = 'You have been deleted'
        logging.info('%s has been deleted' % user.email())

        template_values = {
            'user' : coreuser,
            'base_url': self.request.application_url,
            'message': message,
            'logout_url': users.CreateLogoutURL(self.request.uri),
            }
        self.generate(template_values, 'register.html')


class CoreUserRegister(core.BaseRequestHandler):

    def get(self):
        # Check if the guest is already joined
        user = users.get_current_user()
        logging.debug(user.email())
        coreuser = CoreUser.all().filter('user =', user).get()

        if not coreuser:
            # Create the registration view
            message = None
        else:
            message = "You are already registered in <a href='%s'>TextLocutor!</a>" % self.request.application_url

        template_values = {
            'user' : user,
            'base_url': self.request.application_url,
            'message': message,
            'logout_url': users.CreateLogoutURL(self.request.uri),
            }
        self.generate(template_values, 'register.html')

    def post(self):
        user = users.get_current_user()
        # Check if the guest is already joined
        coreuser = CoreUser.all().filter('user =', user).get()

        if coreuser:
            message = "You are already registered in <a href='%s'>TextLocutor!</a>" % self.request.application_url
        else:
            coreuser = CoreUser(user=user, nick=user.nickname())
            coreuser.put()

            # Before use as reference, coreuser must be saved
            for app in core_settings.EXTRA_APPS:
                module = __import__('%s.models' % app)
                try:
                    module.models.init_user_db(coreuser)
                except AttributeError:
                    # This exception is raised when the app doesn't need
                    # any initialization
                    pass

            message = "Your account has been activated. Go to <a href='%s'>TextLocutor!</a>" % self.request.application_url

        template_values = {
            'user' : coreuser,
            'base_url': self.request.application_url,
            'message': message,
            'logout_url': users.CreateLogoutURL(self.request.uri),
            }
        self.generate(template_values, 'register.html')
        

class CoreUserResetToken(core.BaseRequestHandler):

    def get(self):
        reset_token(self)
        self.redirect(self.request.host_url, True)
